🎖️GitЯра🎖️
Node / meshtastic / Meshtastic-Android / files / core / service / src / commonMain / kotlin / org / meshtastic / core / service / MeshServiceOrchestrator.kt
Displaying Raw • Download
core/service/src/commonMain/kotlin/org/meshtastic/core/service/MeshServiceOrchestrator.kt a31fa287e29db2a5713a771de2d1503eb2f5fcfe (a31fa287) Text, 10.59 KB
T8b949e/*
* Copyright (c) 2026 Meshtastic LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
Tff7b72package T7ee787org.meshtastic.core.service
Tff7b72import T7ee787co.touchlab.kermit.Logger
Tff7b72import T7ee787co.touchlab.kermit.Severity
Tff7b72import T7ee787kotlinx.atomicfu.atomic
Tff7b72import T7ee787kotlinx.coroutines.CoroutineScope
Tff7b72import T7ee787kotlinx.coroutines.SupervisorJob
Tff7b72import T7ee787kotlinx.coroutines.cancel
Tff7b72import T7ee787kotlinx.coroutines.flow.first
Tff7b72import T7ee787kotlinx.coroutines.flow.launchIn
Tff7b72import T7ee787kotlinx.coroutines.flow.onEach
Tff7b72import T7ee787kotlinx.coroutines.isActive
Tff7b72import T7ee787kotlinx.coroutines.launch
Tff7b72import T7ee787org.koin.core.annotation.Single
Tff7b72import T7ee787org.meshtastic.core.common.database.DatabaseManager
Tff7b72import T7ee787org.meshtastic.core.common.util.handledLaunch
Tff7b72import T7ee787org.meshtastic.core.common.util.isValidDeviceAddress
Tff7b72import T7ee787org.meshtastic.core.common.util.safeCatching
Tff7b72import T7ee787org.meshtastic.core.di.CoroutineDispatchers
Tff7b72import T7ee787org.meshtastic.core.repository.MeshConnectionManager
Tff7b72import T7ee787org.meshtastic.core.repository.MeshMessageProcessor
Tff7b72import T7ee787org.meshtastic.core.repository.MeshNotificationManager
Tff7b72import T7ee787org.meshtastic.core.repository.NodeManager
Tff7b72import T7ee787org.meshtastic.core.repository.RadioInterfaceService
Tff7b72import T7ee787org.meshtastic.core.repository.ServiceStateWriter
Tff7b72import T7ee787org.meshtastic.core.repository.TakPrefs
Tff7b72import T7ee787org.meshtastic.core.takserver.TAKMeshIntegration
Tff7b72import T7ee787org.meshtastic.core.takserver.TAKServerManager
T8b949e/**
* Platform-agnostic orchestrator for the mesh service lifecycle.
*
* Extracts the startup wiring previously embedded in Android's `MeshService.onCreate()` into a reusable component. Both
* Android's foreground `Service` and the Desktop `main()` function can use this to start/stop the mesh service graph.
*
* All injected dependencies are `commonMain` interfaces with real implementations in `core:data`.
*/
Tf0883e@SuppressTb4b4b4(Ta5d6ff"Ta5d6ffLongParameterListTa5d6ff"Tb4b4b4)
Tf0883e@Single
Tff7b72class T56d364MeshServiceOrchestratorTb4b4b4(
Tff7b72private Tff7b72val Te6edf3radioInterfaceServiceTb4b4b4: Te6edf3RadioInterfaceServiceTb4b4b4,
Tff7b72private Tff7b72val Te6edf3serviceStateWriterTb4b4b4: Te6edf3ServiceStateWriterTb4b4b4,
Tff7b72private Tff7b72val Te6edf3nodeManagerTb4b4b4: Te6edf3NodeManagerTb4b4b4,
Tff7b72private Tff7b72val Te6edf3messageProcessorTb4b4b4: Te6edf3MeshMessageProcessorTb4b4b4,
Tff7b72private Tff7b72val Te6edf3serviceNotificationsTb4b4b4: Te6edf3MeshNotificationManagerTb4b4b4,
Tff7b72private Tff7b72val Te6edf3takServerManagerTb4b4b4: Te6edf3TAKServerManagerTb4b4b4,
Tff7b72private Tff7b72val Te6edf3takMeshIntegrationTb4b4b4: Te6edf3TAKMeshIntegrationTb4b4b4,
Tff7b72private Tff7b72val Te6edf3takPrefsTb4b4b4: Te6edf3TakPrefsTb4b4b4,
Tff7b72private Tff7b72val Te6edf3databaseManagerTb4b4b4: Te6edf3DatabaseManagerTb4b4b4,
Tff7b72private Tff7b72val Te6edf3connectionManagerTb4b4b4: Te6edf3MeshConnectionManagerTb4b4b4,
Tff7b72private Tff7b72val Te6edf3dispatchersTb4b4b4: Te6edf3CoroutineDispatchersTb4b4b4,
Tb4b4b4) Tb4b4b4{
T8b949e// Per-start coroutine scope. A fresh scope is created on each start() and cancelled on stop(), so all collectors
T8b949e// launched from start() are torn down cleanly and do not accumulate across start/stop/start cycles.
T8b949e// Held in an atomic ref so concurrent start()/stop() callers serialize on compareAndSet rather than racing through
T8b949e// a check-then-set on a plain var.
Tff7b72private Tff7b72val Te6edf3scopeRef Tff7b72= Te6edf3atomicTff7b72<Te6edf3CoroutineScope?Tff7b72>Tb4b4b4(Tff7b72nullTb4b4b4)
T8b949e/** Whether the orchestrator is currently running. */
Tff7b72val Te6edf3isRunningTb4b4b4: Tffa657Boolean
Tff7b72getTb4b4b4(Tb4b4b4) Tff7b72= Te6edf3scopeRefTb4b4b4.Te6edf3valueTff7b72?.Te6edf3isActive Tff7b72=Tff7b72= Tff7b72true
T8b949e/**
* Starts the mesh service components and wires up data flows.
*
* This is the KMP equivalent of `MeshService.onCreate()`. It connects to the radio and wires incoming radio data to
* the message processor.
*/
Tff7b72fun Td2a8ffstartTb4b4b4(Tb4b4b4) Tb4b4b4{
Tff7b72val Te6edf3newScope Tff7b72= Te6edf3CoroutineScopeTb4b4b4(Te6edf3SupervisorJobTb4b4b4(Tb4b4b4) Tff7b72+ Te6edf3dispatchersTb4b4b4.Te6edf3defaultTb4b4b4)
T8b949e// Atomic claim — if another thread already installed a live scope, abandon ours.
Tff7b72if Tb4b4b4(Tff7b72!Te6edf3scopeRefTb4b4b4.Te6edf3compareAndSetTb4b4b4(Te6edf3expect Tff7b72= Tff7b72nullTb4b4b4, Te6edf3update Tff7b72= Te6edf3newScopeTb4b4b4)Tb4b4b4) Tb4b4b4{
Tff7b72val Te6edf3existing Tff7b72= Te6edf3scopeRefTb4b4b4.Te6edf3value
Tff7b72if Tb4b4b4(Te6edf3existingTff7b72?.Te6edf3isActive Tff7b72=Tff7b72= Tff7b72trueTb4b4b4) Tb4b4b4{
Te6edf3LoggerTb4b4b4.Te6edf3d Tb4b4b4{ Ta5d6ff"Ta5d6ffstart() called while already running, ignoringTa5d6ff" Tb4b4b4}
Tff7b72return
Tb4b4b4}
T8b949e// The slot held a dead scope (post-stop). CAS-replace it to avoid racing with another caller.
Tff7b72if Tb4b4b4(Tff7b72!Te6edf3scopeRefTb4b4b4.Te6edf3compareAndSetTb4b4b4(Te6edf3expect Tff7b72= Te6edf3existingTb4b4b4, Te6edf3update Tff7b72= Te6edf3newScopeTb4b4b4)Tb4b4b4) Tb4b4b4{
Te6edf3LoggerTb4b4b4.Te6edf3d Tb4b4b4{ Ta5d6ff"Ta5d6ffstart() lost race replacing dead scope, ignoringTa5d6ff" Tb4b4b4}
Te6edf3newScopeTb4b4b4.Te6edf3cancelTb4b4b4(Tb4b4b4)
Tff7b72return
Tb4b4b4}
Tb4b4b4}
Te6edf3LoggerTb4b4b4.Te6edf3i Tb4b4b4{ Ta5d6ff"Ta5d6ffStarting mesh service orchestratorTa5d6ff" Tb4b4b4}
T8b949e// Drop any bytes that piled up in the service's receivedData channel since the last stop(). The channel
T8b949e// outlives the orchestrator's per-start scope, so without this drain a stop/start cycle would replay stale
T8b949e// packets ahead of the fresh session's firmware handshake.
Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3resetReceivedBufferTb4b4b4(Tb4b4b4)
Te6edf3serviceNotificationsTb4b4b4.Te6edf3initChannelsTb4b4b4(Tb4b4b4)
Te6edf3connectionManagerTb4b4b4.Te6edf3updateStatusNotificationTb4b4b4(Tb4b4b4)
T8b949e// Observe TAK server pref to start/stop
Te6edf3takPrefsTb4b4b4.Te6edf3isTakServerEnabled
Tb4b4b4.Te6edf3onEach Tb4b4b4{ Te6edf3isEnabled Tff7b72-Tff7b72>
Tff7b72if Tb4b4b4(Te6edf3isEnabled Tff7b72&Tff7b72& Tff7b72!Te6edf3takServerManagerTb4b4b4.Te6edf3isRunningTb4b4b4.Te6edf3valueTb4b4b4) Tb4b4b4{
Te6edf3LoggerTb4b4b4.Te6edf3i Tb4b4b4{ Ta5d6ff"Ta5d6ffTAK Server enabled by preference, starting integrationTa5d6ff" Tb4b4b4}
Te6edf3takMeshIntegrationTb4b4b4.Te6edf3startTb4b4b4(Te6edf3newScopeTb4b4b4)
Tb4b4b4} Tff7b72else Tff7b72if Tb4b4b4(Tff7b72!Te6edf3isEnabledTb4b4b4) Tb4b4b4{
Te6edf3LoggerTb4b4b4.Te6edf3i Tb4b4b4{ Ta5d6ff"Ta5d6ffTAK Server disabled by preference, stopping integrationTa5d6ff" Tb4b4b4}
Te6edf3takMeshIntegrationTb4b4b4.Te6edf3stopTb4b4b4(Tb4b4b4)
Tb4b4b4}
Tb4b4b4}
Tb4b4b4.Te6edf3launchInTb4b4b4(Te6edf3newScopeTb4b4b4)
T8b949e// Cold-start lifecycle invariant: a transport must NOT start for a selected address until
T8b949e// the active DB has been switched to that same address. We enforce the ordering
T8b949e// (valid address -> DB switch -> connect) by waiting for currentDeviceAddressFlow to
T8b949e// surface a real selected address before performing the DB switch and connecting the
T8b949e// radio. Address sync inside SharedRadioInterfaceService now runs independently of
T8b949e// connect() (via its init{} listener), so this wait completes as soon as prefs load —
T8b949e// without it, connect() would race ahead of the DB switch and the firmware handshake
T8b949e// would write into the wrong (or null) DB.
T8b949e//
T8b949e// If no device is ever selected this suspends indefinitely for the lifetime of newScope;
T8b949e// by design the radio must not connect without a selected device. This mirrors
T8b949e// MeshService's foreground-service stay-alive gate (isValidDeviceAddress).
Te6edf3newScopeTb4b4b4.Te6edf3handledLaunch Tb4b4b4{
Tff7b72val Te6edf3address Tff7b72= Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3currentDeviceAddressFlowTb4b4b4.Te6edf3firstTb4b4b4(Tff7b72::Te6edf3isValidDeviceAddressTb4b4b4)
Te6edf3databaseManagerTb4b4b4.Te6edf3switchActiveDatabaseTb4b4b4(Te6edf3addressTb4b4b4)
T8b949e// Load cached nodes from the now-active per-device DB before connect() so the firmware
T8b949e// handshake doesn't see a stale/empty node set. Previously this ran synchronously in
T8b949e// start() and raced ahead of the DB switch, reading the default (or null) DB.
Te6edf3nodeManagerTb4b4b4.Te6edf3loadCachedNodeDBTb4b4b4(Tb4b4b4)
Te6edf3LoggerTb4b4b4.Te6edf3i Tb4b4b4{ Ta5d6ff"Ta5d6ffPer-device database initialized, connecting radioTa5d6ff" Tb4b4b4}
Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3connectTb4b4b4(Tb4b4b4)
Tb4b4b4}
T8b949e// Mid-session device-address transitions (late process-lifecycle devAddr propagation,
T8b949e// user-initiated device switch, etc.): keep the active DB in sync with the selected
T8b949e// device. The initial emission (matching the .first() snapshot above) is an idempotent
T8b949e// no-op in DatabaseManager. wrap in safeCatching so a single transient failure (e.g. Room
T8b949e// I/O error) doesn't kill the collector and silently halt ALL future address propagation
T8b949e// for the lifetime of this orchestrator scope. safeCatching re-throws CancellationException
T8b949e// so scope cancellation still propagates cleanly.
T8b949e//
T8b949e// Note: cold-start ordering (valid address -> DB switch -> connect) is enforced above,
T8b949e// but a mid-session device switch via setDeviceAddress() races this DB switch against the
T8b949e// transport restart. Pre-existing behavior, not introduced by the lifecycle refactor.
Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3currentDeviceAddressFlow
Tb4b4b4.Te6edf3onEach Tb4b4b4{ Te6edf3addr Tff7b72-Tff7b72>
Te6edf3safeCatching Tb4b4b4{ Te6edf3databaseManagerTb4b4b4.Te6edf3switchActiveDatabaseTb4b4b4(Te6edf3addrTb4b4b4) Tb4b4b4}
Tb4b4b4.Te6edf3onFailure Tb4b4b4{ Te6edf3err Tff7b72-Tff7b72> Te6edf3LoggerTb4b4b4.Te6edf3eTb4b4b4(Te6edf3errTb4b4b4) Tb4b4b4{ Ta5d6ff"Ta5d6ffFailed to switch active database on address updateTa5d6ff" Tb4b4b4} Tb4b4b4}
Tb4b4b4}
Tb4b4b4.Te6edf3launchInTb4b4b4(Te6edf3newScopeTb4b4b4)
Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3receivedData
T8b949e// This loop is the single lifeline for every inbound packet. handleFromRadio is already total, but guard
T8b949e// here too so nothing — now or later — can cancel the collection and leave the radio permanently deaf.
Tb4b4b4.Te6edf3onEach Tb4b4b4{ Te6edf3frame Tff7b72-Tff7b72>
Tff7b72val Te6edf3session Tff7b72= Te6edf3frameTb4b4b4.Te6edf3session
Tff7b72if Tb4b4b4(Tff7b72!Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3isSessionActiveTb4b4b4(Te6edf3sessionTb4b4b4)Tb4b4b4) Tb4b4b4{
Te6edf3LoggerTb4b4b4.Te6edf3d Tb4b4b4{ Ta5d6ff"Ta5d6ffDropping queued frame from stale transport session gen=Tffd700${Te6edf3sessionTb4b4b4.Te6edf3generationTffd700}Ta5d6ff" Tb4b4b4}
Tff7b72returnTf0883e@onEach
Tb4b4b4}
Te6edf3safeCatching Tb4b4b4{ Te6edf3messageProcessorTb4b4b4.Te6edf3handleFromRadioTb4b4b4(Te6edf3frameTb4b4b4, Te6edf3nodeManagerTb4b4b4.Te6edf3myNodeNumTb4b4b4.Te6edf3valueTb4b4b4) Tb4b4b4}
Tb4b4b4.Te6edf3onFailure Tb4b4b4{ Te6edf3LoggerTb4b4b4.Te6edf3eTb4b4b4(Tffa657itTb4b4b4) Tb4b4b4{ Ta5d6ff"Ta5d6ffDropped inbound frame after a receive-loop errorTa5d6ff" Tb4b4b4} Tb4b4b4}
Tb4b4b4}
Tb4b4b4.Te6edf3launchInTb4b4b4(Te6edf3newScopeTb4b4b4)
Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3connectionError
Tb4b4b4.Te6edf3onEach Tb4b4b4{ Te6edf3errorMessage Tff7b72-Tff7b72> Te6edf3serviceStateWriterTb4b4b4.Te6edf3setErrorMessageTb4b4b4(Te6edf3errorMessageTb4b4b4, Te6edf3SeverityTb4b4b4.Te6edf3WarnTb4b4b4) Tb4b4b4}
Tb4b4b4.Te6edf3launchInTb4b4b4(Te6edf3newScopeTb4b4b4)
Tb4b4b4}
T8b949e/**
* Stops the mesh service components and cancels the coroutine scope.
*
* This is the KMP equivalent of `MeshService.onDestroy()`.
*/
Tff7b72fun Td2a8ffstopTb4b4b4(Tb4b4b4) Tb4b4b4{
Te6edf3LoggerTb4b4b4.Te6edf3i Tb4b4b4{ Ta5d6ff"Ta5d6ffStopping mesh service orchestratorTa5d6ff" Tb4b4b4}
Te6edf3takMeshIntegrationTb4b4b4.Te6edf3stopTb4b4b4(Tb4b4b4)
T8b949e// Best-effort polite goodbye on service teardown (onDestroy / process shutdown). We launch
T8b949e// on a fresh detached scope — not the orchestrator's per-start scope — so the subsequent
T8b949e// scope.cancel() below doesn't interrupt the short drain delay inside disconnect(). The
T8b949e// coroutine is fire-and-forget; typical runtime is ~100-150ms which comfortably fits
T8b949e// inside Android's onDestroy() grace window.
Te6edf3CoroutineScopeTb4b4b4(Te6edf3SupervisorJobTb4b4b4(Tb4b4b4) Tff7b72+ Te6edf3dispatchersTb4b4b4.Te6edf3defaultTb4b4b4)Tb4b4b4.Te6edf3launch Tb4b4b4{
Te6edf3runCatching Tb4b4b4{ Te6edf3radioInterfaceServiceTb4b4b4.Te6edf3disconnectTb4b4b4(Tb4b4b4) Tb4b4b4}
Tb4b4b4}
Te6edf3scopeRefTb4b4b4.Te6edf3getAndSetTb4b4b4(Tff7b72nullTb4b4b4)Tff7b72?.Te6edf3cancelTb4b4b4(Tb4b4b4)
Tb4b4b4}
Tb4b4b4}
Served by rngit 1.5.0 - Generated in 0.06s